<template>
  <div class="stay-container">
    <LayoutHeaderTitle title="确认订单" />
    <!-- 地址 -->
    <nuxt-link
      v-if="!address"
      class="no-address"
      :to="{ name: 'user-addAddress' }"
    >
      去添加收货地址
      <van-icon name="arrow" />
    </nuxt-link>
    <nuxt-link v-else class="address" :to="{ name: 'user-address' }">
      <div class="info">
        <van-icon name="location" />
        <div class="address-info">
          <p class="name">{{ address.name }}</p>
          <p class="text-over">{{ address.address }}</p>
          <p>手机号：{{ address.tel }}</p>
        </div>
      </div>
      <van-icon name="arrow" />
    </nuxt-link>
    <!-- 商品列表 -->
    <div class="cart-list">
      <ul>
        <template v-if="type === 'cart'">
          <li v-for="item in cartList" :key="item.b_id">
            <div class="head">
              <nuxt-link :to="item.b_id | storeUrl">
                {{ item.b_name }} <van-icon name="arrow" />
              </nuxt-link>
            </div>
            <div class="item" v-for="c in item.list" :key="c.cart_id">
              <div class="info">
                <nuxt-link :to="c.g_id | goodsUrl">
                  <img :src="c.g_src | formatSrc" :alt="c.g_name" />
                </nuxt-link>
                <div class="content">
                  <nuxt-link :to="c.g_id | goodsUrl" class="text-over2 name">
                    {{ c.g_name }}
                  </nuxt-link>
                  <p class="spec text-over">
                    {{ c.spec_name }}
                  </p>
                  <p class="right gary">
                    数量：{{ c.num }} / 单价：
                    {{ c.discounted_price || c.sell_price }}
                  </p>
                  <p class="sum right">
                    总价：{{
                      getSumPrice(c.num, c.discounted_price || c.sell_price)
                    }}
                  </p>
                </div>
              </div>
            </div>
          </li>
        </template>
        <template v-else>
          <li>
            <div class="head">
              <nuxt-link :to="goodsInfo.b_id | storeUrl">
                {{ goodsInfo.b_name }} <van-icon name="arrow" />
              </nuxt-link>
            </div>
            <div class="item">
              <div class="info">
                <nuxt-link :to="goodsInfo.g_id | goodsUrl">
                  <img
                    :src="goodsInfo.g_src | formatSrc"
                    :alt="goodsInfo.g_name"
                  />
                </nuxt-link>
                <div class="content">
                  <nuxt-link
                    :to="goodsInfo.g_id | goodsUrl"
                    class="text-over2 name"
                  >
                    {{ goodsInfo.g_name }}
                  </nuxt-link>
                  <p class="spec text-over">
                    {{ goodsInfo.spec_name }}
                  </p>
                  <p class="right gary">
                    数量：{{ goodsInfo.num }} / 单价：
                    {{ goodsInfo.discounted_price || goodsInfo.sell_price }}
                  </p>
                  <p class="sum right">
                    总价：{{
                      getSumPrice(
                        goodsInfo.num,
                        goodsInfo.discounted_price || goodsInfo.sell_price
                      )
                    }}
                  </p>
                </div>
              </div>
            </div>
          </li>
        </template>
      </ul>
    </div>
    <div class="total">
      <span>合计:</span>
      <span class="text">{{ allPrice }}</span>
      <van-button round type="danger" @click="submit">结算</van-button>
    </div>
    <LayoutLoad :show="pageLoadding" />
  </div>
</template>

<script>
export default {
  middleware: "authenticated",
  layout: "notabbar",
  async asyncData({ redirect, params, app, from }) {
    let addressList = [],
      cartList = [];

    if (!from) return redirect({ name: "index" });
    const { type, list, goodsInfo } = params;
    if (type === "cart") {
      if (!list || !Array.isArray(list) || list.length === 0) {
        return redirect({ name: "cart" });
      }
      cartList = list;
    } else if (type === "goods") {
      if (!goodsInfo) {
        return redirect(from);
      }
    } else {
      return redirect(from);
    }

    try {
      const { data, status } = await app.$apiGetAddress();
      if (status === 0) addressList = data;
    } catch (error) {
      console.log(error);
    }
    return { addressList, cartList, goodsInfo, type };
  },
  data() {
    return {
      addressList: [],
      cartList: [],
      pageLoadding: false,
      goodsInfo: {},
      type: ""
    };
  },
  methods: {
    // 点击 结算按钮
    submit() {
      if (!this.address) {
        this.$toast({ message: "请添加收货地址", type: "fail" });
        this.$router.push({ name: "user-addAddress" });
        return;
      }
      const list = this.cartList.reduce((a, c) => a.concat(c.list), []);
      this.pageLoadding = true;
      const data = { addressInfo: this.address, cartList: list };
      setTimeout(() => {
        this.$toast.success({
          message: "跳过支付环节",
          onOpened: () => {
            this.pageLoadding = false;
          },
          onClose: () => {
            if (this.type === "cart") {
              this.addOrder(data);
            } else {
              this.goodsToOrder();
            }
          }
        });
      }, 1000);
    },
    // 购物车页面 进来的 结算
    addOrder(data) {
      data.address_id = this.address.address_id;
      this.$apiAddOrder(data).then(res => {
        const { status } = res;
        if (status === 0) {
          this.$router.replace({ name: "order" });
        }
      });
    },
    // 算出商品总价
    getSumPrice(num, price) {
      const sum = price * num;
      return /\./g.test(sum) ? Number(sum.toFixed(2)) : sum;
    },
    // 商品页进来的 结算
    goodsToOrder() {
      const goodsInfo = {
        num: this.goodsInfo.num,
        g_id: this.goodsInfo.g_id,
        sell_price: this.goodsInfo.sell_price,
        spec_id: this.goodsInfo.spec_id,
        b_id: this.goodsInfo.b_id,
        discounted_price: this.goodsInfo.discounted_price
      };
      const data = {
        addressInfo: this.address,
        goodsInfo
      };
      this.$apiGoodsToOrder(data).then(res => {
        const { status } = res;
        if (status === 0) {
          this.$router.replace({ name: "order" });
        }
      });
    }
  },
  computed: {
    address() {
      if (this.addressList.length) {
        let defaultAddress = this.addressList.find(a => a.isDefault);
        return defaultAddress || this.addressList[0];
      }
      return null;
    },
    allPrice() {
      if (this.type === "cart") {
        const sum = this.cartList.reduce((a, item) => {
          return (
            a +
            item.list.reduce(
              (a, item) =>
                a +
                this.getSumPrice(
                  item.num,
                  item.discounted_price || item.sell_price
                ),
              0
            )
          );
        }, 0);
        return /\./g.test(sum) ? sum.toFixed(2) : sum;
      } else {
        return this.getSumPrice(
          this.goodsInfo.num,
          this.goodsInfo.discounted_price || this.goodsInfo.sell_price
        );
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.stay-container {
  padding: 50px 10px;
  height: 100vh;
  overflow-y: auto;
  box-sizing: border-box;
  font-size: 16px;
  background: #f3f3f3;
  .no-address,
  .address {
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 10px;
    border: 1px solid #c8c7cc;
    border-radius: 10px;
    box-sizing: border-box;
    background: #fff;
    color: #000;
  }
  .info {
    display: flex;
    width: 300px;
    align-items: center;
    .address-info {
      margin-left: 10px;
      width: 85%;
      .name {
        font-size: 16px;
        color: #000;
      }
      p {
        margin: 0;
        font-size: 12px;
        color: #9f9b9b;
      }
    }
  }
  .total {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 0 20px;
    height: 50px;
    line-height: 50px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    background: #fff;
    font-size: 16px;
    .text {
      color: red;
      padding: 0 10px 0 5px;
    }
    ::v-deep button {
      height: 30px;
    }
  }
}
.cart-list {
  font-size: 16px;
  padding: 20px 10px;
  a {
    color: #000;
  }
  li {
    background: #fff;
    margin-bottom: 20px;
    border-radius: 10px;
  }

  .head {
    padding: 10px 10px 0;
    display: flex;
    font-weight: bold;
    margin-bottom: 5px;
    ::v-deep .van-icon-arrow {
      vertical-align: middle;
    }
    a {
      display: flex;
      align-items: center;
      margin-left: 10px;
    }
  }
  .content {
    width: 170px;
  }

  .item {
    display: flex;
    padding: 10px;
    margin-bottom: 10px;
    font-size: 14px;
    &.disabled {
      background: #f3f3f3;
    }
  }
  .info {
    margin-left: 10px;
    display: flex;
    align-items: flex-start;
    color: #000;
    img {
      width: 120px;
      height: 120px;
      margin-right: 10px;
    }
    .name {
      font-weight: 400;
    }
    p {
      margin: 0;
    }
    .spec {
      margin-top: 10px;
      padding: 2px 5px;
      display: inline-block;
      max-width: 160px;
      font-size: 12px;
      background: #e9e9e9;
    }
    .right {
      font-size: 12px;
      text-align: right;
    }
    .gary {
      color: #b3b3b3;
    }
    .sum {
      margin-top: 10px;
      font-size: 16px;
      font-weight: bold;
      color: red;
    }
  }
}
</style>
